<?php
class ProductController extends MainController implements ControllerInterface {

	//o - order
	//v - order vector
	//t - total items to select
	public $tableConfig = array(
		'product_table_main' => array(
			'o' => array(
				'id' => 'product.id_product',
				'serial' => 'product.code',
				'name' => 'product_description.name',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 10
		),
		'infopts_table' => array(
			'o' => array(
				'id' => 'image_map.id_image_map',
				'name' => 'image_map_description.title',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 10
		)
	);

	public function preDispatch($param) {
		$this->Run($param);
		$this->RunShared('Auth', array());
		$this->smarty->assign('param_from_url',$param);
		$this->smarty->assign('languages',LanguageDAL::GetResult(LanguageDAL::GetDalDataobj(array('sortBy' => 'id_language ASC', 'condition'=>array('active'=>'1')))));
		$this->smarty->assign('manufacturers',ManufacturerDAL::GetResult(ManufacturerDAL::GetDalDataObj(array('sortBy' => 'name ASC', 'condition' => array('active' => array('value' => 1))))));
		$this->smarty->assign('categories',CategoryDAL::getAdminCategoryTree());
	}

	public function postDispatch($param) {

	}



	public function IndexAction($param) {
//		Utils::ArrayDisplay($this->tableParams['product_table']);
		$lang = Registry::Get('default_language_id');
		$dal = ProductDAL::GetDalDataObj(array(
			'tableData' => $this->tableParams['product_table_main'],
			'join' => array(
				'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = '.Registry::Get('default_language_id').')'
			)
		));

		if(Request::IsPost() && Request::Check('id_manufacturer')) {
			$data = Request::GetAllPost();
			SessionProxy::SetValue('product_filter',serialize($data));
			$this->addRedirect(Router::GenerateUrl('productIndex',array('product' => 'index')),0);
		}

		if(SessionProxy::IsSetValue('product_filter')) {
			$data = SessionProxy::GetValue('product_filter');
			$data = unserialize($data);

			$filtering = false;

			if($data['id_manufacturer'] > 0) {
				$dal->addCondition('id_manufacturer',$data['id_manufacturer']);
				$filtering = true;
			}

			if($data['id_category'] > 0) {
				$dal->addCondition('id_category',$data['id_category']);
				$filtering = true;
			}

			if(strlen($data['code']) > 0) {
				$dal->addCondition('code',$data['code']);
				$filtering = true;
			}

			if(strlen($data['name']) > 0) {
				$dal->addCondition('product_description.name',"'%".$data['name']."%'",'LIKE');
				$filtering = true;
			}

			if($filtering){
				$this->smarty->assign('filter',$data);
			}else{
				SessionProxy::ClearValue('product_filter');
			}
		}

		$list = ProductDAL::GetResult($dal);
		$dal->setCount(true);
		$dal->setLimit('');
		$count = ProductDAL::GetResult($dal);

		$this->smarty->assign('list',$list);
		$this->smarty->assign('c',$count);
	}

	public function PhotoAction($param) {
		
	}
	
	
	public function AddAction($param) {
		if(Request::IsPost()) {
			$product = new Product();
			$product->setActive(Request::GetPost('active'));
			$product->setCode(Request::GetPost('code'));
			$name = Request::GetPost('name');
			$name = is_array($name)?array_shift($name):$name;
			$product->setSlug(ProductDAL::GenerateUniqueSlug($name));
			$product->setIdManufacturer(Request::GetPost('id_manufacturer'));
			$product->setIdCategory(Request::GetPost('id_category'));
			$product->setProfessionalist($_POST['professionalist']);

			if(isset($_FILES['main_image']) && is_uploaded_file($_FILES['main_image']['tmp_name'])) {
				$img = imagecreatefromstring(file_get_contents($_FILES['main_image']['tmp_name']));
				if($img !== false) {
					if(!is_dir(PATH_STATIC_CONTENT . 'upload/product'))
						mkdir(PATH_STATIC_CONTENT . 'upload/product',0777,true);

					$fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['main_image']['name']);

					$temp = $fileName;
					$counter = 0;
					while(is_file(PATH_STATIC_CONTENT . 'upload/product/'.$temp))
						$temp = ++$counter.'_'.$fileName;

					$fileName = $temp;
					
					move_uploaded_file($_FILES['main_image']['tmp_name'], PATH_STATIC_CONTENT . 'upload/product/' . $fileName);
					$product->setMainImage('upload/product/' . $fileName);
				}
			}
			
			$dalCheck = ProductDAL::GetDalDataObj();
			$dalCheck->addCondition('id_category', $product->getIdCategory());
			$dalCheck->setOrderBy('rank DESC');
			$dalCheck->setLimit('1');
			$productCheck = ProductDAL::GetResult($dalCheck);
			if(isset($productCheck[0])) {
				$product->setRank(($productCheck[0]->getRank()+1));
			} else {
				$product->setRank('1');
			}
			
			if(isset($_POST['disable_rank'])) {
				$product->setRank('0');
			}

			$id_product = ProductDAL::Insert($product->getDalDataobj());

			$data = Request::GetAllPost();

			if(isset($data['name']) && is_array($data['name'])) {
				foreach(array_keys($data['name']) AS $id_language) {
					$productDescription = new ProductDescription();
					$productDescription->setIdProduct($id_product);
					$productDescription->setIdLanguage($id_language);
					$productDescription->setDescription(Request::GetPost('description_'.$id_language,false));
					$productDescription->setTechnologies(Request::GetPost('technologies_'.$id_language,false));
					$productDescription->setName($data['name'][$id_language]);
					$productDescription->setSeoKeywords($data['seo_keywords'][$id_language]);
					$productDescription->setSeoDescription($data['seo_description'][$id_language]);
					ProductDescriptionDAL::Insert($productDescription->getDalDataObj());
				}
			}

			$this->addRedirect(Router::GenerateUrl('productIndex',array('Product' => 'Index')),0);
		}
	}

	public function EditAction($param) {
		$product = ProductDAL::GetResult(ProductDAL::GetDalDataobj(array('condition' => array(
			'id_product' => array($param['id'])
		))));
		$product = $product[0];
		
		if(isset($_GET['photo'])) {
			$dalD = ProductImageDAL::GetDalDataObj();
			$dalD->addCondition('id_product_image', $_GET['photo']);
			$obj = ProductImageDAL::GetResult($dalD);
			//var_dump($obj);
			if(isset($obj[0])) {
				$dalD->setObj($obj[0]);
				ProductImageDAL::Delete($dalD);
			}
		}
		
		if(isset($_GET['video'])) {
			$dalD = ProductVideoDAL::GetDalDataObj();
			$dalD->addCondition('id_product_video', $_GET['video']);
			$obj = ProductVideoDAL::GetResult($dalD);
			if(isset($obj[0])) {
				$dalD->setObj($obj[0]);
				ProductVideoDAL::Delete($dalD);
			}
		}
		
		$dalObj = ProductImageDAL::GetDalDataObj();
			$dalObj->addCondition('active', '1');
			$dalObj->addCondition('id_product', $product->getId());
			$images = ProductImageDAL::GetResult($dalObj);
			
		$this->smarty->assign('productImages', $images);
		
		$dalObj = ProductVideoDAL::GetDalDataObj();
			$dalObj->addCondition('active', '1');
			$dalObj->addCondition('id_product', $product->getId());
			$videos = ProductVideoDAL::GetResult($dalObj);
			
		$this->smarty->assign('productVideo', $videos);

		if(Request::IsPost()) {
			$product->setActive(Request::GetPost('active'));
			$product->setCode(Request::GetPost('code'));
			$name = Request::GetPost('name');
			$name = is_array($name)?array_shift($name):$name;
			$product->setSlug(ProductDAL::GenerateUniqueSlug($name, $product->getSlug()));
			$product->setIdManufacturer(Request::GetPost('id_manufacturer'));
			if((int)$product->getIdCategory() != (int)Request::getPost('id_category')) {
				Registry::Get('db')->prepare('DELETE FROM property_value WHERE id_product = '.$product->getId())->execute();
			}
			$product->setIdCategory(Request::GetPost('id_category'));
			$product->setProfessionalist($_POST['professionalist']);

			if(isset($_FILES['main_image']) && is_uploaded_file($_FILES['main_image']['tmp_name'])) {
				$img = imagecreatefromstring(file_get_contents($_FILES['main_image']['tmp_name']));
				if($img !== false) {
					if(!is_dir(PATH_STATIC_CONTENT . 'upload/product'))
						mkdir(PATH_STATIC_CONTENT . 'upload/product',0777,true);

					$fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['main_image']['name']);

					$temp = $fileName;
					$counter = 0;
					while(is_file(PATH_STATIC_CONTENT . 'upload/product/'.$temp))
						$temp = ++$counter.'_'.$fileName;

					$fileName = $temp;

					move_uploaded_file($_FILES['main_image']['tmp_name'], PATH_STATIC_CONTENT . 'upload/product/' . $fileName);
					$product->setMainImage('upload/product/' . $fileName);
				}
			}

			if(isset($_POST['disable_rank'])) {
				$product->setRank('0');
			} else {
				if($product->getRank()=='0') {
					$dalCheck = ProductDAL::GetDalDataObj();
					$dalCheck->addCondition('id_category', $product->getIdCategory());
					$dalCheck->setOrderBy('rank DESC');
					$dalCheck->setLimit('1');
					$productCheck = ProductDAL::GetResult($dalCheck);
					if(isset($productCheck[0])) {
						$product->setRank(($productCheck[0]->getRank()+1));
					} else {
						$product->setRank('1');
					}
				}
			}
			
			ProductDAL::Save($product->getDalDataobj());
			$id_product = $param['id'];

			$data = Request::GetAllPost();

			if(isset($data['name']) && is_array($data['name'])) {
				foreach(array_keys($data['name']) AS $id_language) {
					$productDescription = $product->getDescription($id_language);
					$productDescription->setIdLanguage($id_language);
					$productDescription->setDescription(Request::GetPost('description_'.$id_language,false,false));
					$productDescription->setTechnologies(Request::GetPost('technologies_'.$id_language,false,false));
					$productDescription->setName($data['name'][$id_language]);
					$productDescription->setSeoKeywords($data['seo_keywords'][$id_language]);
					$productDescription->setSeoDescription($data['seo_description'][$id_language]);
					ProductDescriptionDAL::Save($productDescription->getDalDataObj());
				}
			}

			
			if(!isset($_FILES['gallery_image']) && !is_uploaded_file($_FILES['gallery_image']['tmp_name']) 
					&& (!isset($_POST['video']) || $_POST['video']=='')) {
				$this->addRedirect(Router::GenerateUrl('productIndex',array('Product' => 'Index')),0);
			} else {
				$redirect = false;
				if(isset($_FILES['gallery_image']) && is_uploaded_file($_FILES['gallery_image']['tmp_name'])) {
					$img = imagecreatefromstring(file_get_contents($_FILES['gallery_image']['tmp_name']));
					if($img !== false) {
						if(!is_dir(PATH_STATIC_CONTENT . 'upload/product/'.$product->getId()))
							mkdir(PATH_STATIC_CONTENT . 'upload/product/'.$product->getId(),0777,true);

						$fileName = preg_replace('~[^\\pL\d\.]+~u', '-', $_FILES['gallery_image']['name']);

						$temp = $fileName;
						$counter = 0;
						while(is_file(PATH_STATIC_CONTENT . 'upload/product/'.$product->getId().'/'.$temp))
							$temp = ++$counter.'_'.$fileName;

						$fileName = $temp;

						move_uploaded_file($_FILES['gallery_image']['tmp_name'], PATH_STATIC_CONTENT . 'upload/product/'.$product->getId().'/' . $fileName);
						//$product->setMainImage('upload/product/' . $fileName);
						$imageDal = ProductImageDAL::GetDalDataObj();
						$image = new ProductImage();
						$image->setIdProduct($product->getId());
						$image->setActive(1);
						$image->setImage('upload/product/'.$product->getId().'/' . $fileName);
						$imageDal->setObj($image);
						ProductImageDAL::Save($imageDal);
						$redirect = true;
					}
				}
				
				if(isset($_POST['video']) && $_POST['video']!='') {
					$videoDal = ProductVideoDAL::GetDalDataObj();
					$video = new ProductVideo();
					$video->setActive(1);
					$video->setIdProduct($product->getId());
					$video->setCode($_POST['video']);
					$videoDal->setObj($video);
					ProductVideoDAL::Save($videoDal);
					$redirect = true;
				}
				
				if($redirect)$this->addRedirect(Router::GenerateUrl('',array('product' => 'edit', 'id'=>$product->getId())).'#galery',0);
			}
			
			$dalData = ProductRankingTypeDAL::GetDalDataObj();
		$dalData->addCondition('active', '1');
		$productRankingType = ProductRankingTypeDAL::GetResult($dalData);
		$prT = array();
		foreach($productRankingType as $p) {
			$prT[] = $p->getId();
		}
		
		$dalData = ProductRankingDAL::GetDalDataObj();
		$dalData->addCondition('type', ' ( '.implode(',', $prT).' ) ', ' IN ');
		$dalData->addCondition('id_product', $product->getId());
		$productRanking = ProductRankingDAL::GetResult($dalData);
		$prV = array();
		foreach($productRanking as $pr) {
			$dalData->setObj($pr);
			ProductRankingDAL::Delete($dalData);
		}
	//	var_dump($_POST);die();
		if(isset($_POST['productRankingType'])) {
		foreach($_POST['productRankingType'] as $prD => $v) {
			$newPrd = new ProductRanking();
			$newPrd->setIdProduct($product->getId());
			$newPrd->setType($prD);
			$newPrd->setIdCategory($product->getIdCategory());
			$dalData->setObj($newPrd);
			
			ProductRankingDAL::Save($dalData);
		}
		}
			$this->addRedirectInfo('Zmiany zostały zapisane','ok',Router::GenerateUrl('productIndex',array('product' => 'index')),0);
		}
		
		
		$dalData = ProductRankingTypeDAL::GetDalDataObj();
		$dalData->addCondition('active', '1');
		$productRankingType = ProductRankingTypeDAL::GetResult($dalData);
		$prT = array();
		foreach($productRankingType as $p) {
			$prT[] = $p->getId();
		}
		
		$this->smarty->assign('productRankingType', $productRankingType);
		
		$dalData = ProductRankingDAL::GetDalDataObj();
		$dalData->addCondition('type', ' ( '.implode(',', $prT).' ) ', ' IN ');
		$dalData->addCondition('id_product', $product->getId());
		$productRanking = ProductRankingDAL::GetResult($dalData);
		$prV = array();
		foreach($productRanking as $pr) {
			$prV[$pr->getType()]=true;
		}
		
		$this->smarty->assign('productRanking', $prV);
		$this->smarty->assign('obj',$product);
	}

	public function InfoptsAction($param) {
		$this->addScript('infopts.js');
		$obj = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array(
			'condition' => array(
				'id_product' => array($param['id'])
			)
		)));
		$this->smarty->assign('obj',$obj[0]);

		if(!is_file(PATH_STATIC_CONTENT .''.$obj[0]->getMainImage())) {
			$this->addRedirectInfo('Aby edytować info-punkty najpierw musisz wgrać obraz.','error',Router::GenerateUrl('productIndex',array('Product' => 'Index')));
			return;
		}

		if(Request::IsPost() && Request::Check('addPoint')) {
			$this->smarty->assign('x',Request::GetPost('x'));
			$this->smarty->assign('y',Request::GetPost('y'));
			$this->smarty->assign('h',Request::GetPost('h'));
			$this->smarty->assign('w',Request::GetPost('w'));
			$this->smarty->assign('addNew',1);
		}else{
			if(Request::isPost() && Request::Check('confirmAdd')) {
				$imageMap = new ImageMap();
				$imageMap->setIdProduct($param['id']);
				$imageMap->setX(Request::GetPost('x'));
				$imageMap->setY(Request::GetPost('y'));
				$imageMap->setH(Request::GetPost('h'));
				$imageMap->setW(Request::GetPost('w'));
				$imageMap->setActive(Request::GetPost('active'));

				$id = ImageMapDAL::Insert($imageMap->getDalDataObj());

				$data = Request::GetAllPost();

				if(isset($data['name']) && is_array($data['name'])) {
					foreach(array_keys($data['name']) AS $id_language) {
						$productDescription = new ImageMapDescription();
						$productDescription->setIdLanguage($id_language);
						$productDescription->setDescription(Request::GetPost('description_'.$id_language,false,false));
						$productDescription->setTitle($data['name'][$id_language]);
						$productDescription->setIdImageMap($id);
						ImageMapDescriptionDAL::Save($productDescription->getDalDataObj());
					}
				}
				$this->addRedirect(Router::generateurl('productInfopts',array('product' => 'infopts', 'id' => $param['id'])),0);
			}

			$lang = Registry::Get('default_language_id');
			$list = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array(
				'condition' => array(
					'id_product' => array($param['id'])
				),
				'tableData' => $this->tableParams['infopts_table'],
				'join' => array(
					'ImageMapDescription' => ' LEFT JOIN image_map_description ON(image_map.id_image_map = image_map_description.id_image_map AND image_map_description.id_language = '.Registry::Get('default_language_id').')'
				)
			)));
			$count = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array(
				'condition' => array(
					'id_product' => array($param['id'])
				),
				'count' => true
				)));

			$this->smarty->assign('list',$list);
			$this->smarty->assign('c',$count);
		}
	}

	public function RemoveAction($param) {
		$this->setNoRender();
		$imageMap = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array('condition' => array('id_product' => array($param['id'])))));

		$id = 0;

		foreach($imageMap AS $item) {

			ProductDAL::Delete($item->getDalDataObj());
		}

		$this->addRedirect(Router::Generateurl('productIndex',array('product' => 'index')),0);
	}

	public function InfoptsRemoveAction($param) {
		$this->setNoRender();
		$imageMap = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array('condition' => array('id_image_map' => array($param['id'])))));

		$id = 0;

		foreach($imageMap AS $item) {
			$id = $item->getIdProduct();

			ImageMapDAL::Delete($item->getDalDataObj());
		}

		$this->addRedirect(Router::Generateurl('productInfopts',array('product' => 'infopts', 'id' => $id)),0);
	}

	public function InfoptsEditAction($param) {
		$this->addScript('infopts.js');
		$this->partialTemplate = 'InfoptsEdit.tpl';
		$map = ImageMapDAL::GetResult(ImageMapDAL::GetDalDataObj(array('condition' => array('id_image_map' => array($param['id'])))));
		$obj = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array('condition' => array('id_product' => array($map[0]->getIdProduct())))));


		if(Request::isPost() && Request::Check('confirmAdd')) {
			$imageMap = $map[0];
			//$imageMap->setIdProduct($param['id']);
			$imageMap->setX(Request::GetPost('x'));
			$imageMap->setY(Request::GetPost('y'));
			$imageMap->setH(Request::GetPost('h'));
			$imageMap->setW(Request::GetPost('w'));
			$imageMap->setActive(Request::GetPost('active'));

			$id = ImageMapDAL::Save($imageMap->getDalDataObj());

			$data = Request::GetAllPost();

			if(isset($data['title']) && is_array($data['title'])) {
				foreach(array_keys($data['title']) AS $id_language) {
					$productDescription = $imageMap->getDescription($id_language);
					$productDescription->setIdLanguage($id_language);
					$productDescription->setDescription(Request::GetPost('description_'.$id_language,false,false));
					$productDescription->setTitle($data['title'][$id_language]);
					ImageMapDescriptionDAL::Save($productDescription->getDalDataObj());
				}
			}
			$this->addRedirect(Router::generateurl('productInfopts',array('product' => 'infopts', 'id' => $obj[0]->getId())),0);
		}


		$this->smarty->assign('map' , $map[0]);
		$this->smarty->assign('obj' , $obj[0]);
	}
}

